package 第十二章_反射与内省.introspector_内省;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.Properties;
public class BeanFactory {
    //生成一个对象 用来使用properties这个类
    private static Properties prop =new Properties();
    static{
        //1.getResourceAsStream   作用:拿路径转字节流      把路径文件转换成inputstream （读取文件并转成字节码）
        //2.getContextclassLoader 作用:通用版lib的规则（谁有用谁，递归顺序）通用lib文件加载字节码  自定义->app->ext->boot   看谁的库里有合适的类 没有就递归给最开始的库执行
        try {
            InputStream in=Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("第十二章_反射与内省/introspector_内省/config.properties"); //路径是/ 不是.
            //读取字节流并且转成键值对
            prop.load(in);

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Object getBean(String name){
        Object bean=null;
        String beanName=prop.getProperty(name);
        try {
            Class<?> aClass = Class.forName(beanName);
            bean=aClass.newInstance();
            //通过类信息获取JAVABEAN的描述信息
            BeanInfo beanInfo = Introspector.getBeanInfo(aClass);
            //通过javabean的描述信息，获取该类的所有属性描述器
            PropertyDescriptor[] propertyDescriptors=beanInfo.getPropertyDescriptors();
            for(int i=0;i<propertyDescriptors.length;i++){
                String propertyName=propertyDescriptors[i].getName();
                Method writeMethod=propertyDescriptors[i].getWriteMethod();

                if("username".equals(propertyName)){
                    writeMethod.invoke(bean,prop.getProperty("bean.username"));
                }else if("password".equals((propertyName))) {
                    writeMethod.invoke(bean, prop.getProperty("bean.password"));
                }else if("url".equals(propertyName)){
                    writeMethod.invoke(bean,prop.getProperty("bean.url"));
                }
            }

        } catch (ClassNotFoundException | IntrospectionException | InvocationTargetException | IllegalAccessException |
                 InstantiationException e) {
            throw new RuntimeException(e);
        }
        return bean;
    }

}
